package io.github.rascaler.dcenter.platforms.binance;

import io.github.rascaler.dcenter.constant.ConstantItem;
import io.github.rascaler.dcenter.db.DbManager;
import io.github.rascaler.dcenter.platforms.DbMapper;
import io.github.rascaler.dcenter.pojo.Candlestick;
import io.github.rascaler.dcenter.pojo.FixedArrayList;
import io.github.rascaler.dcenter.pojo.Instrument;
import io.github.rascaler.dcenter.utils.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName BinanceDbProxy
 * @Description TODO
 * @Author wurenqing
 * @Date 2023-12-08 14:16
 */
@Component
public class BinanceDbMapperImpl implements DbMapper {

    @Autowired
    private DbManager dbManager;

    @Resource(type = BinanceDbMapperImpl.class)
    private DbMapper dbMapper;

    public Map<String, Long> getTimeMap(String frequency) {
        Map<String, Long> result = new HashMap<>();
        dbManager.getMdb().getInstrumentMap().forEach((s,val) -> {
            String key = String.format(BinanceConstant.keyTemplate, val.getSymbol(), frequency, ConstantItem.ADJUST_NO, ConstantItem.EXCHANGE_BINANCE);
            FixedArrayList<Candlestick> bars = dbManager.getMdb().getBarMap().get(key);
            if (CollectionUtils.isEmpty(bars)) {
                return;
            }else{
                result.put(val.getSymbol(), bars.get(bars.size()-1).getBarDate());
            }
        });
        return result;
    }

    @Override
    public List<String> getNeedInitSymbols(String frequency) {
        List<String> needInitSymbols = new ArrayList<>();
        Map<String, Long> map = getTimeMap(frequency);
        Long now = System.currentTimeMillis();
        dbManager.getMdb().getInstrumentMap().forEach((key, val) ->{
            Long dateTime = map.get(key);
            if (null == dateTime || now - dateTime > 4 * 60 * 60 * 1000 ) {
                needInitSymbols.add(val.getSymbol());
            }
        });
        return needInitSymbols;
    }

    @Override
    public List<Instrument> selectAllInstruments() {
        Collection<Instrument> instruments =  dbManager.getMdb().getInstrumentMap().values();
        return CollectionUtils.isEmpty(instruments) ? new ArrayList<>() : new ArrayList<>(instruments);
    }
}
